package com.onlygx.dva.common.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.onlygx.dva.common.constant.MsgConstant;
import com.onlygx.dva.common.utils.RequestLogUtil;
import com.onlygx.dva.common.entity.dto.CoreUserDTO;
import com.onlygx.dva.common.exception.FailRequestException;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 瞳见科技，用户未登录验证
 *
 * @author : GaoXiang
 * 时间 : 2021/12/29
 * 介绍 :
 */
@Component
@RequiredArgsConstructor
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@Nonnull HttpServletRequest request,@Nonnull HttpServletResponse response,@Nonnull Object handler){

        CoreUserDTO coreUserDTO = RequestLogUtil.getRequestUser(request);
        if(ObjectUtil.isNotNull(coreUserDTO) && StrUtil.isNotEmpty(coreUserDTO.getUid())){
            return true;
        }
        response.setStatus(HttpStatus.SC_OK);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        try {
            response.getWriter().write(MsgConstant.USER_NOT_LOGIN);
        } catch (IOException e) {
            e.printStackTrace();
            throw new FailRequestException();
        }
       return false;
    }
}
